package com.xgp.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        test4();
    }

    /**
     * 抛出异常
     */
    public static void test1() {
        //队列的大小
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(arrayBlockingQueue.add("a"));
        System.out.println(arrayBlockingQueue.add("b"));
        System.out.println(arrayBlockingQueue.add("c"));
//        System.out.println(arrayBlockingQueue.add("d"));

        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
    }

    /**
     * 不抛出异常
     */
    public static void test2() {
        //队列的大小
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(arrayBlockingQueue.offer("a"));
        System.out.println(arrayBlockingQueue.offer("b"));
        System.out.println(arrayBlockingQueue.offer("c"));
        System.out.println(arrayBlockingQueue.offer("c"));

        System.out.println(arrayBlockingQueue.element());       //查看队首的元素
        System.out.println(arrayBlockingQueue.peek());          //查看队首的元素

        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
    }

    /**
     * 一直阻塞
     */
    public static void test3() throws InterruptedException {
        //队列的大小
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);

        //一直阻塞
        arrayBlockingQueue.put("a");
        arrayBlockingQueue.put("b");
        arrayBlockingQueue.put("c");
//        arrayBlockingQueue.put("d");

        System.out.println(arrayBlockingQueue.take());
        System.out.println(arrayBlockingQueue.take());
        System.out.println(arrayBlockingQueue.take());
        System.out.println(arrayBlockingQueue.take());
    }

    /**
     * 超时退出
     * @throws InterruptedException
     */
    public static void test4() throws InterruptedException {
        //队列的大小
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);

        //一直阻塞
        arrayBlockingQueue.offer("a", 1,TimeUnit.SECONDS);
        arrayBlockingQueue.offer("b", 1,TimeUnit.SECONDS);
        arrayBlockingQueue.offer("c", 1,TimeUnit.SECONDS);
        arrayBlockingQueue.offer("d", 1,TimeUnit.SECONDS);

        System.out.println(arrayBlockingQueue.poll(1, TimeUnit.SECONDS));
        System.out.println(arrayBlockingQueue.poll(1, TimeUnit.SECONDS));
        System.out.println(arrayBlockingQueue.poll(1, TimeUnit.SECONDS));
        System.out.println(arrayBlockingQueue.poll(1, TimeUnit.SECONDS));
        System.out.println(arrayBlockingQueue.poll(1, TimeUnit.SECONDS));


    }
}
